package com.zuqiuzhandui.liveing.net;

import com.code19.library.DateUtils;
import com.code19.library.L;
import com.code19.library.SPUtils;
import com.zuqiuzhandui.BuildConfig;
import com.zuqiuzhandui.liveing.common.MyApplication;
import com.zuqiuzhandui.liveing.common.UserInfomationManage;
import com.zuqiuzhandui.liveing.myInterfacce.Constant;
import com.zuqiuzhandui.testing.myhelper.util.HashMapProxy;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by Mc on 2016/7/13.
 */
public class UrlFactory implements Constant {
    public final String V = "v";
    public final String v = "0.1";
    public final String APP_KEY = "appKey";
    public final String TIME_STAMPS = "timestamp";
    public final String testAppKey = "MODULE-20140629174446096";  //测试账户
    public final String testAppSecret = "z3aUdadaU2cmAeAA";       //测试账户
    public final String formalAppKey="RF5S6TV9FSMUDCIX27W7I8PSDINWHAPH";
    public final String formalAppSecret="06B8AEF8010E8F2DE91A4D61F8BB6F4F";
    public String appkey;
    public String appSecret;
    public final String sdfStr = "yyyy-MM-dd HH:mm:ss";

    private String url;
    public Map<String,String> map;
    public String mBaseUrl;

    public UrlFactory(String url) {
        initBaseUrl();
        this.url = mBaseUrl + url;
        map=new TreeMap<>();
        appedDefulParams();
    }

    /**
     * 设置不同的环境
     */
    private void initBaseUrl() {
        if (BuildConfig.LOG_DEBUG) {
            //正式环境
            mBaseUrl=BASE_URL2;
            appkey=formalAppKey;
            appSecret=formalAppSecret;
        }
        else {
//            mBaseUrl=baseUrl2;
//            mBaseUrl=baseUrl2;
            mBaseUrl=BASE_URL;
            appkey=testAppKey;
            appSecret=testAppSecret;
        }
    }

    /**
     * 添加固定的参数
     */
    private void appedDefulParams() {
        int a=url.indexOf("=");
        String value=url.substring(url.indexOf("=")+1);
        map.put("method",url.substring(url.indexOf("=")+1));
        putParams(V, v);
        putParams(APP_KEY, appkey);
        putParams(TIME_STAMPS, DateUtils.formatDateCustom(new Date(), sdfStr));
        putParams("signMethod","md5");
        putParams("format","json");
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void putParams(String key, String value) {
        url = url + "&" + key + "=" + value;
        map.put(key,value);
    }



    /**
     * @param map 请求的业务参数
     */
    public UrlFactory setSecret(Map map){
        //对map集合进行排序
        Map<String, String> orderMap = new TreeMap<>();
        orderMap.putAll(map);
        orderMap.putAll(this.map);

        //把参数封装到url中
        Set<Map.Entry<String, String>> set = orderMap.entrySet();
        StringBuffer sb = new StringBuffer();
        sb.append(appSecret);
        for (Map.Entry<String, String> param : set) {
            if (param.getValue() != null) {
                sb.append(param.getKey()).append(param.getValue());
            }
        }
        sb.append(appSecret);
        L.d(sb.toString());
        //使用MD5加密
        byte[] bytes;
        try {
            bytes = encryptMD5(sb.toString());
            putParams("sign", byte2hex(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this;
    }


    private static byte[] encryptMD5(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes(CHARSET_UTF8));
        } catch (GeneralSecurityException gse) {
            String msg = getStringFromException(gse);
            throw new IOException(msg);
        }
        return bytes;
    }

    private static String getStringFromException(Throwable e) {
        String result = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);
        e.printStackTrace(ps);
        try {
            result = bos.toString(CHARSET_UTF8);
        } catch (IOException ioe) {
        }
        return result;
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static Map<String,String> getAccessKeyMap() {
        Map<String,String> map=new HashMapProxy<>();
        map.put("accessKey", UserInfomationManage.getAccessKey());
        return map;
    }
}
